package com.ruoyi.chengji.controller;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.domain.server.Sys;
import com.ruoyi.pingjiao.domain.Score;
import com.ruoyi.pingjiao.domain.Term;
import com.ruoyi.pingjiao.domain.TermScore;
import com.ruoyi.pingjiao.service.ScoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("score")
public class ScoreController extends BaseController {
    @Autowired
    private ScoreService scoreService;
    @Autowired
    private ServerConfig serverConfig;
    @PostMapping("import")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file,@RequestParam("courseId") Long courseId) throws IOException {
        String url=null;
        String pathName=null;
        if(file!=null){
            String filePath = RuoYiConfig.getUploadPath();
            String upload = FileUploadUtils.upload(filePath, file);

            url=filePath+file.getOriginalFilename();
//            String replace = url.replace("/profile","");
//            System.out.println(replace);
            File file1=new File(filePath);
            if(!file1.exists()){
                file1.mkdir();
            }
            file.transferTo(new File(url));
//            pathName=filePath+upload;
            System.out.println(url);
//            file.transferTo(new File(pathName));
        }
        scoreService.importExcel(url,courseId);

        return AjaxResult.success();
    }
    /**
     * 下载导入模板
     */
    @PostMapping("downloadExcel")
    public void downloadExcel(HttpServletResponse httpServletResponse) {
        InputStream inputStream = null;
        try (ServletOutputStream outputStream = httpServletResponse.getOutputStream()) {
            //设置响应头信息，包括下载后的文件名和编码等
            httpServletResponse.addHeader("content-disposition", String.format("attachment;filename= %s", URLEncoder.encode("导入模板.xlsx", "utf-8")));
            httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            httpServletResponse.setCharacterEncoding("UTF-8");
            //在文件夹里获取到文件并转为流
            String filePath = "test/doc/moban.xlsx";
//            URL resourceUrl = getClass().getClassLoader().getResource(filePath);
//            String resourcePath = resourceUrl.getPath();
//            String filePath1 = URLDecoder.decode(resourcePath, "UTF-8");
            inputStream = new ClassPathResource(filePath).getInputStream();
            byte[] b = streamToByteArray(inputStream);
            httpServletResponse.getOutputStream().write(b);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static byte[] streamToByteArray(InputStream in) throws Exception {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int n;
        while (-1 != (n = in.read(buffer))) {
            output.write(buffer, 0, n);
        }
        return output.toByteArray();
    }
    //查询所有数据
    @GetMapping("list")
    public TableDataInfo list(Score score){
        startPage();
        List<Score>scores= scoreService.list(score);
        return getDataTable(scores);
    }

    @GetMapping("student/check")
    public TableDataInfo checkScore(){
        startPage();
        List<Term> termScores = scoreService.checkScore();
        return getDataTable(termScores);
    }

    //添加
    @PostMapping("add")
    public AjaxResult add(@RequestBody Score score){
        return toAjax(scoreService.add(score));
    }
    //修改
    @PutMapping("update")
    public AjaxResult update(@RequestBody Score score){
        return toAjax(scoreService.updateInfo(score));
    }
    //删除
    @DeleteMapping("{id}")
    public AjaxResult delete(@PathVariable Long id){
        return toAjax(scoreService.delete(id));
    }

    @GetMapping("getScore/{courseId}")
    public AjaxResult getScore(@PathVariable Integer courseId){

        return AjaxResult.success(scoreService.getScoreByCourseId(courseId));
    }
}
